package com.springboot.quanxian.controller.sys;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.util.MapUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.springboot.quanxian.common.DictionaryEnum;
import com.springboot.quanxian.entity.SysManager;
import com.springboot.quanxian.service.ISysManagerRoleService;
import com.springboot.quanxian.service.ISysManagerService;
import com.springboot.quanxian.service.ISysRoleMenuService;
import com.springboot.quanxian.util.RandomValidateCodeUtil;
import com.springboot.quanxian.util.ResultView;
import com.springboot.quanxian.util.RsaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Validated
@RestController
@RequestMapping("/api/admin/login")
public class AdminLoginController {

    @Autowired
    private ISysManagerRoleService iHjManagerRoleService;

    @Autowired
    private ISysRoleMenuService iHjRoleMenuService;

    @Autowired
    private ISysManagerService iHjManagerService;


    @PostMapping("/adLogin")
    public ResultView adLogin(@NotEmpty(message = "账号不能为空") String account,
                              @NotEmpty(message = "密码不能为空") String pwd,
                              @NotEmpty(message = "登录类型不能为空") String roleId,
                              @NotEmpty(message = "验证码不能为空") String code, HttpServletRequest request){
        String sysCode = (String)request.getSession().getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);
        if(request.getSession().getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY)==null || request.getSession().getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY).equals("")){
            return ResultView.error("验证码已过期");
        }
        if(!sysCode.equalsIgnoreCase(code)) {
            return ResultView.error("验证码填写错误");
        }
        QueryWrapper<SysManager> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("m_account",account);
        queryWrapper.eq("role_id",roleId);
        SysManager hjManager=this.iHjManagerService.getOne(queryWrapper);
        if(hjManager==null){
            return ResultView.error("账号不存在！！！");
        }
        if(!RsaUtil.getRsaPwd(hjManager.getMPwd()).equalsIgnoreCase(pwd)){
            return ResultView.error("密码错误");
        }
        //进行授权注入sa-token权限框架
        StpUtil.login(hjManager.getManagerId());
        return ResultView.ok(StpUtil.getTokenValue());
    }

    /**
     * 注册
     * @param obj
     * @return
     */
    @PostMapping("/register")
    public ResultView register(SysManager obj){
        return this.iHjManagerService.register(obj);
    }

    /**
     * 生成验证码
     */
    @GetMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
        randomValidateCode.getRandcode(request, response);//输出验证码图片方法
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping(value = "/getAccountInfo")
    public ResultView getAccountInfo() {
        Map<String, Object> map = MapUtils.newHashMap();
        String managerId=StpUtil.getLoginIdAsString();
        map.put("user",this.iHjManagerService.getById(managerId));
        SysManager sysManager=this.iHjManagerService.getById(managerId);
        List<String> permissions = new ArrayList<>();
        List<String> roles =new ArrayList<>();
        if(sysManager.getMAccount().equals("admin")){
            roles.add("admin");
            permissions.add("*:*:*");
            map.put("permissions",permissions);
            map.put("roles",roles);
        }else{
            List<String> menuList=iHjRoleMenuService.getMenuList(managerId);
            for (String menuPerm : menuList) {
                if(!StringUtils.isEmpty(menuPerm)){
                    permissions.add(menuPerm);
                }
            }
            map.put("permissions",permissions);
            List<String> roleList=iHjManagerRoleService.getRoleList(managerId);
            for (String rolePerm : roleList) {
                if(!StringUtils.isEmpty(rolePerm)){
                    roles.add(rolePerm);
                }
            }
            map.put("roles",roles);
        }
        return ResultView.ok(map);
    }

    /**
     * 生成验证码
     */
    @PostMapping(value = "/logout")
    public ResultView logout(HttpServletRequest request, HttpServletResponse response) {
        if(StpUtil.isLogin()){
            StpUtil.logout(StpUtil.getLoginIdAsString());
        }
        return ResultView.ok();
    }

}
